package h0909;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
  * @description 全排列II
  * @author 不知名帅哥
  * @date 2024/9/9 22:59
  * @version 1.0
*/
public class AllPermutations {
    public static void main(String[] args) {
        int[] nums={1,1,2};
        System.out.println(permuteUnique(nums));
    }
    public static List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> res=new ArrayList<>();
        LinkedList<Integer> temp=new LinkedList<>();
        Arrays.sort(nums);
        boolean[] used=new boolean[nums.length];
        backTrack(res,temp,used,nums);
        return res;
    }

    private static void backTrack(List<List<Integer>> res, LinkedList<Integer> temp, boolean[] used,int[] nums) {
        if (temp.size()== nums.length){
            res.add(new LinkedList<>(temp));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if (i>0&&nums[i]==nums[i-1]&&!used[i-1]) continue;
            if (!used[i]){
                temp.addLast(nums[i]);
                used[i]=true;
                backTrack(res, temp, used, nums);
                used[i]=false;
                temp.removeLast();
            }
        }
    }
}
